<template>
  <div>
    <el-form ref="spuForm" :model="spuInfo" :rules="rules" label-width="80">
      <el-form-item label="SPU名称" prop="spuName">
        <el-input v-model="spuInfo.spuName" placeholder="请输入SPU名称" />
      </el-form-item>
      <el-form-item label="SPU品牌" prop="tmId">
        <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
          <el-option v-for="trademark in trademarkList" :key="trademark.id" :label="trademark.tmName" :value="trademark.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input v-model="spuInfo.description" type="textarea" placeholder="请输入SPU描述" />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload action="/dev-api/admin/product/fileUpload" :class="{'spu-image-upload': spuImageList.length>=3}" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept=".jpg,.png,.jpeg" :limit="3" :file-list="spuImageList">
          <i class="el-icon-plus">
            <div slot="tip" class="el-upload__tip">只能上传JPG、PNG、JPEG 格式图片,且不超过3M</div>
          </i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="30%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还剩下${formatBaseSaleAttrList.length}个属性`">
          <el-option v-for="baseSaleAttr in formatBaseSaleAttrList" :key="baseSaleAttr.id" :label="baseSaleAttr.name" :value="baseSaleAttr.name" />
        </el-select>
        <el-button type="primary" :disabled="!spuInfo.spuSaleAttr" icon="el-icon-plus" style="margin-left:10px" @click="addSpuSaleAttr">添加销售属性值</el-button>
        <el-table border :data="spuInfo.spuSaleAttrList" style="margin-top:10px">
          <el-table-column type="index" lable="序号" align="center" width="80" />
          <el-table-column lable="属性名" prop="saleAttrName" />
          <el-table-column lable="属性值列表">
            <template v-slot="{row}">
              <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.saleAttrValueName" closable :disable-transitions="false" @close="handleClose(row, index)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input v-if="row.inputVisible" ref="saveTagInput" v-model="inputValue" class="input-new-tag" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)" />
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加详细</el-button>
            </template>
          </el-table-column>
          <el-table-column lable="操作">
            <template v-slot="{$index}">
              <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteSpuSaleAttr($index)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="$emit('update:visible', 1)">取消</el-button>
      </el-form-item>
    </el-form>
    </el-form>
  </div>
</template>
<script>
import { reqGetAllTrademarkList, reqGetBaseSaleAttrList, reqSaveSpuInfo, reqGetSpuImageList, reqGetSpuSaleAttrList, reqUpdateSpuInfo } from '@/api/product/spu'
import { mapState } from 'vuex'

export default {
  name: 'SaveSpu',
  props: {
    currentSpuInfo: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    const spuImageListValidate = (rule, value, callback) => {
      // console.log(value)
      // if (!value.length) {
      //   callback('请上传spu图片')
      //   return
      // }
      callback()
    }
    const spuSaleAttrListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一个属性')
        if (!value.every(item => item.spuSaleAttrValueList.length > 0)) {
          callback('请至少添加一个详细属性')
        }
        return
      }
      callback()
    }
    return {
      inputVisible: false, // 控制按钮与输入框切换的
      inputValue: '', // 表单中用于双向数据绑定 或是说用于收集数据的
      dialogImageUrl: '', // 图片的链接
      dialogVisible: false, // 上传图片成功后的预览
      trademarkList: [], // 所有的品牌数据列表
      baseSaleAttrList: [], // 所有的基础销售属性列表
      spuImageList: [],
      spuInfo: {
        spuSaleAttr: '', // 选择的基本的销售属性名  颜色 规格  尺寸中的一个
        // 此对象是用来存储要上传的spu相关的属性信息的
        spuName: '', // 要添加的SPU属性名称
        tmId: '', // SPU所属的品牌
        description: '', // SPU的描述
        spuImageList: [], // 上传照片墙链接地址
        spuSaleAttrList: [], // 获取基本销售属性数据
        // category3Id: ''
        ...this.currentSpuInfo
      },
      rules: {
        spuName: [{ required: true, message: '请输入spu名称', trigger: 'blur' }],
        tmId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        spuImageList: [{ required: true, validator: spuImageListValidate }],
        spuSaleAttrList: [{ required: true, validator: spuSaleAttrListValidate }]
      }
    }
  },
  computed: {
    formatBaseSaleAttrList() {
      return this.baseSaleAttrList.filter(baseSaleAttr => {
        return !this.spuInfo.spuSaleAttrList.find(item => baseSaleAttr.name === item.saleAttrName)
      })
    },
    formartSpuImageList() {
      return this.spuImageList.map(item => {
        return {
          name: item.imgName,
          url: item.imgUrl
        }
      })
    },
    ...mapState('category', ['category3Id'])
  },
  async mounted() {
    try {
      const { id } = this.spuInfo
      let promises = [reqGetAllTrademarkList(), reqGetBaseSaleAttrList()]
      if (id) {
        promises = promises.concat([reqGetSpuImageList(id), reqGetSpuSaleAttrList(id)])
      }
      console.log(promises, 'promises')
      const [resTrademarkList, resBaseSaleAttrList, resSpuImageList, resSpuSaleAttrList] = await Promise.all(promises)
      this.trademarkList = resTrademarkList.data
      this.baseSaleAttrList = resBaseSaleAttrList.data
      if (resSpuImageList && resSpuImageList.code === 200) {
        this.spuImageList = resSpuImageList.data
        this.spuInfo.spuSaleAttrList = resSpuSaleAttrList.data
      }
    } catch (e) {
      this.$message.error('获取数据出错...')
    }
  },
  methods: {
    // 删除图片时调用的函数
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      this.spuImageList = fileList
    },
    // 预览图片时调用的函数
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传成功后，会调用此方法
    handleAvatarSuccess(res, file, fileList) {
      // console.log('success', res, file)
      // 收集上传的图片
      console.log(fileList)
      this.spuImageList = fileList
      // // 上传图片成功之后，移除校验提示
      // this.$refs.tmForm.clearValidate(['logoUrl'])
      this.$refs.spuForm.clearValidate(['spuImageList'])
    },
    // 上传之前会调用 此方法
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const imgArr = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = imgArr.includes(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    // 删除动态编辑标签相关
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
    },
    showInput(row) {
      this.$set(row, 'inputVisible', true)
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加了输入值之后，失去焦点后的效果
    handleInputConfirm(row) {
      const inputValue = this.inputValue
      if (inputValue) {
        // row.spuSaleAttrValueList.push(inputValue)
        if (row.spuSaleAttrValueList.find(item => item.saleAttrValueName === inputValue)) {
          this.$message.error('属性值已经存在了，请更换一个...')
          row.inputVisible = false
          this.inputValue = ''
          return
        }
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrName: row.saleAttrName,
          saleAttrValueName: inputValue
        })
      }
      row.inputVisible = false
      this.inputValue = ''
      this.$refs.spuForm.clearValidate(['spuSaleAttrList'])
    },
    // 添加销售属性
    addSpuSaleAttr() {
      const spuSaleAttrList = this.spuInfo.spuSaleAttrList
      // if (spuSaleAttrList.length && spuSaleAttrList[spuSaleAttrList.length - 1].spuSaleAttrValueList.length === 0) {
      //   this.$message.error('请添加具体属性值')
      //   return
      // }
      //
      if (!spuSaleAttrList.every(item => item.spuSaleAttrValueList.length !== 0)) {
        this.$message.error('属性对应的具体值不对')
        return
      }

      // 获取baseSaleAttrId ,其实就是所选销售属性的对应id
      const id = this.baseSaleAttrList.find(item => item.name === this.spuInfo.spuSaleAttr).id
      // this.spuInfo.spuSaleAttrList.push({
      spuSaleAttrList.push({
        baseSaleAttrId: id,
        inputVisible: false,
        saleAttrName: this.spuInfo.spuSaleAttr,
        spuSaleAttrValueList: []
      })
      this.spuInfo.spuSaleAttr = ''
      this.$refs.spuForm.clearValidate(['spuSaleAttrList'])
    },
    deleteSpuSaleAttr(index) {
      this.spuInfo.spuSaleAttrList.splice(index, 1)
    },
    submitForm() {
      this.$refs.spuForm.validate(async valid => {
        if (valid) {
          // alert('submit!')
          this.spuInfo.category3Id = this.category3Id
          this.spuInfo.spuImageList = this.spuImageList.map(item => {
            return {
              imgName: item.name,
              imgUrl: (item.response && item.response.data) || item.url
            }
          })
          if (!this.spuImageList.length) {
            this.$message.error('请至少悬着一张图片')
            return
          }
          const { id } = this.spuInfo
          let result
          if (id) {
            result = await reqUpdateSpuInfo(this.spuInfo)
          } else {
            result = await reqSaveSpuInfo(this.spuInfo)
          }

          if (result.code === 200) {
            this.$message.success(`${id ? '更新' : '添加'}spu成功`)
            this.$emit('setScene', 1)
          } else {
            this.$message.error(`${id ? '更新' : '添加'}失败`)
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
